package com.gx.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gx.mapper.TbBusinessDeployMapper;
import com.gx.model.dto.definition.NodeInfo;
import com.gx.model.pojo.TbBusinessDeploy;
import com.gx.service.TbBusinessDeployService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.RepositoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author lpj
 */
@Service
@Slf4j
public class TbBusinessDeployServiceImpl extends ServiceImpl<TbBusinessDeployMapper, TbBusinessDeploy> implements TbBusinessDeployService {
    @Resource
    private RepositoryService repositoryService;

    /**
     * 新增流程实例关联表单
     *
     * @param deployFormReq 流程实例关联表单
     */
    @Override
    public void insertOrUpdateDeployForm(TbBusinessDeploy deployFormReq) {
        LambdaQueryWrapper<TbBusinessDeploy> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TbBusinessDeploy::getBusinessKey, deployFormReq.getBusinessKey())
                .or()
                .eq(TbBusinessDeploy::getDeployId, deployFormReq.getDeployId());
        //删除关联关系
        this.remove(queryWrapper);
        //获取所有节点信息
        List<Process> processes = repositoryService.getBpmnModel(deployFormReq.getProcessId())
                .getProcesses();
        System.out.println("processes size:" + processes.size());
        for (Process process : processes) {
            Collection<FlowElement> flowElements = process.getFlowElements();
            ArrayList<NodeInfo> nodeInfoList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(flowElements)) {
                for (FlowElement flowElement : flowElements) {
                    if (flowElement instanceof UserTask) {
                        String id = flowElement.getId();
                        String name = flowElement.getName();
                        NodeInfo nodeInfo = new NodeInfo(id, name);
                        nodeInfoList.add(nodeInfo);
                    }
                }
                String nodeInfoJson = JSON.toJSONString(nodeInfoList);
                deployFormReq.setNodeInfo(nodeInfoJson);
                log.info("流程节点信息保存成功:{}", nodeInfoJson);
            }
        }
        //保存流程表单关联
        this.save(deployFormReq);
    }

}